<?php

namespace App\Models;

use App\Models\Traits\Curl;
use App\Models\Traits\RoomInfo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * @author kuddy
 * Class History
 * @package App\Models
 * @property Platform $platformInfo
 * @property string $room_id
 */
class History extends Model
{
    use Curl;
    use RoomInfo;

    protected $fillable = [
        'room_id',
        'owner',
        'url'
    ];

    protected $appends = [
        'pop',
        'src',
        'name',
        'key'
    ];

    public function platformInfo(): BelongsTo
    {
        return $this->belongsTo(Platform::class, 'platform_id');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function getPopAttribute()
    {
        return $this->getRoomDetail('pop');
    }

    public function getSrcAttribute()
    {
        return $this->getRoomDetail('src');
    }

    public function getNameAttribute()
    {
        return $this->getRoomDetail('name');
    }

    public function getKeyAttribute()
    {
        return $this->getRoomDetail('key');
    }

    public function getPlatformAttribute()
    {
        return $this->platformInfo->name;
    }

    protected function getPlatformName(): string
    {
        return $this->platformInfo->name;
    }

    /**
     * @author kuddy
     * @return string
     */
    protected function getUri()
    {
        $uri = $this->getPlatformConfig('uri');
        return $uri . $this->room_id;
    }

    protected function getPlatformConfig($type)
    {
        return config("platform.{$this->getPlatformName()}.detail.$type", []);
    }

    public function updateHistory(array $roomInfo): bool
    {
        $res = false;
        $platform = \Cache::remember('platform:' . $roomInfo['platform'], 1, function () use ($roomInfo) {
            return Platform::where(['name' => $roomInfo['platform']])->firstOrFail();
        });
        $record = $this::newModelInstance()
            ->where('user_id', \Auth::id())
            ->where('platform_id', $platform->id)
            ->where('room_id', $roomInfo['id'])
            ->where('owner', $roomInfo['owner'])
            ->where('url', $roomInfo['url'])
            ->first();
        if (empty($record)) {
            $record = $this->fill([
                'room_id' => $roomInfo['id'],
                'owner'   => $roomInfo['owner'],
                'url'     => $roomInfo['url']
            ]);
            $record->platformInfo()->associate($platform);
            $record->user()->associate(\Auth::user());
        }
        if ($record->save()) {
            $record->increment('clicks');
            $res = true;
        }
        return $res;
    }
}
